import React, { useState, useEffect } from 'react';
import {
  Card, Avatar, Typography, Button, Form, Input, Tabs, Row, Col, Tag, Space, 
  Divider, Tooltip, Upload, notification, Progress, Statistic, Select
} from 'antd';
import {
  UserOutlined, MailOutlined, AimOutlined, EnvironmentOutlined,
  CalendarOutlined, TrophyOutlined, UploadOutlined, EditOutlined,
  CloseOutlined, SaveOutlined, ThunderboltOutlined, HomeOutlined,
  MobileOutlined, GlobalOutlined, BookOutlined, CheckCircleOutlined
} from '@ant-design/icons';
import { useUserStore } from '../../store/userStore';
import type { UploadProps } from 'antd';
import dayjs from 'dayjs';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;

interface UserProfileExtended {
  bio?: string;
  location?: string;
  occupation?: string;
  birthday?: string;
  phone?: string;
  website?: string;
  interests?: string[];
  avatar?: string;
  joinDate?: string;
  carbonReduction?: number;
  treesPlanted?: number;
  tasksCompleted?: number;
  achievements?: number;
}

const UserProfile: React.FC = () => {
  const { user, updateUser } = useUserStore();
  const [isEditing, setIsEditing] = useState(false);
  const [form] = Form.useForm();
  const [extendedProfile, setExtendedProfile] = useState<UserProfileExtended>({
    bio: '环保爱好者，致力于减少碳足迹，为绿色地球贡献自己的力量。',
    location: '上海市',
    occupation: '软件工程师',
    birthday: '1990-01-01',
    phone: '138****5678',
    website: 'https://greenplanet.example.com',
    interests: ['低碳生活', '环保科技', '可持续发展', '户外活动'],
    avatar: '',
    joinDate: '2023-01-15',
    carbonReduction: 127.5,
    treesPlanted: 12,
    tasksCompleted: 36,
    achievements: 8
  });

  useEffect(() => {
    if (user) {
      // 从用户对象加载现有数据
      form.setFieldsValue({
        username: user.username,
        email: user.email,
        ...extendedProfile
      });
    }
  }, [user, form, extendedProfile]);

  const handleEdit = () => {
    setIsEditing(true);
  };

  const handleCancel = () => {
    form.setFieldsValue({
      username: user?.username,
      email: user?.email,
      ...extendedProfile
    });
    setIsEditing(false);
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      
      // 更新用户资料
      if (user) {
        const updatedUser = {
          ...user,
          username: values.username,
          email: values.email
        };
        
        // 更新扩展资料
        setExtendedProfile({
          ...extendedProfile,
          bio: values.bio,
          location: values.location,
          occupation: values.occupation,
          birthday: values.birthday,
          phone: values.phone,
          website: values.website,
          interests: values.interests
        });
        
        updateUser(updatedUser);
        
        notification.success({
          message: '个人资料已更新',
          description: '您的个人资料已成功更新。'
        });
      }
      
      setIsEditing(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const uploadProps: UploadProps = {
    name: 'avatar',
    action: 'http://localhost:3000/api/user/avatar',
    headers: {
      authorization: 'Bearer ' + localStorage.getItem('token'),
    },
    onChange(info) {
      if (info.file.status === 'done') {
        notification.success({
          message: '头像上传成功',
          description: '您的头像已成功更新。'
        });
        // 更新头像URL
        setExtendedProfile({
          ...extendedProfile,
          avatar: info.file.response.url
        });
      } else if (info.file.status === 'error') {
        notification.error({
          message: '头像上传失败',
          description: info.file.response?.message || '上传过程中发生错误'
        });
      }
    },
  };

  return (
    <div style={{ padding: '24px', maxWidth: '1000px', margin: '0 auto' }}>
      <Card bordered={false}>
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            username: user?.username,
            email: user?.email,
            ...extendedProfile
          }}
        >
          <div style={{ textAlign: 'right', marginBottom: '20px' }}>
            {!isEditing ? (
              <Button 
                type="primary" 
                icon={<EditOutlined />} 
                onClick={handleEdit}
              >
                编辑个人资料
              </Button>
            ) : (
              <Space>
                <Button 
                  icon={<CloseOutlined />} 
                  onClick={handleCancel}
                >
                  取消
                </Button>
                <Button 
                  type="primary" 
                  icon={<SaveOutlined />} 
                  onClick={handleSave}
                >
                  保存
                </Button>
              </Space>
            )}
          </div>
          
          <Row gutter={24}>
            {/* 左侧个人信息 */}
            <Col span={8}>
              <div style={{ textAlign: 'center', marginBottom: '24px' }}>
                {isEditing ? (
                  <Upload {...uploadProps}>
                    <div style={{ marginBottom: '10px' }}>
                      <Avatar 
                        size={120} 
                        icon={<UserOutlined />} 
                        src={extendedProfile.avatar} 
                        style={{ cursor: 'pointer' }}
                      />
                    </div>
                    <Button icon={<UploadOutlined />}>上传头像</Button>
                  </Upload>
                ) : (
                  <Avatar 
                    size={120} 
                    icon={<UserOutlined />} 
                    src={extendedProfile.avatar} 
                  />
                )}
                
                <div style={{ marginTop: '16px' }}>
                  <Title level={4}>{user?.username}</Title>
                  <Text type="secondary">{extendedProfile.occupation}</Text>
                </div>
                
                <Divider />
                
                <div style={{ textAlign: 'left' }}>
                  <p>
                    <EnvironmentOutlined style={{ marginRight: '8px' }} />
                    {isEditing ? (
                      <Form.Item name="location" style={{ display: 'inline-block', margin: 0, width: 'calc(100% - 30px)' }}>
                        <Input placeholder="所在地" />
                      </Form.Item>
                    ) : (
                      extendedProfile.location
                    )}
                  </p>
                  
                  <p>
                    <MailOutlined style={{ marginRight: '8px' }} />
                    {isEditing ? (
                      <Form.Item name="email" style={{ display: 'inline-block', margin: 0, width: 'calc(100% - 30px)' }}>
                        <Input placeholder="电子邮箱" />
                      </Form.Item>
                    ) : (
                      user?.email
                    )}
                  </p>
                  
                  <p>
                    <MobileOutlined style={{ marginRight: '8px' }} />
                    {isEditing ? (
                      <Form.Item name="phone" style={{ display: 'inline-block', margin: 0, width: 'calc(100% - 30px)' }}>
                        <Input placeholder="联系电话" />
                      </Form.Item>
                    ) : (
                      extendedProfile.phone
                    )}
                  </p>
                  
                  <p>
                    <GlobalOutlined style={{ marginRight: '8px' }} />
                    {isEditing ? (
                      <Form.Item name="website" style={{ display: 'inline-block', margin: 0, width: 'calc(100% - 30px)' }}>
                        <Input placeholder="个人网站" />
                      </Form.Item>
                    ) : (
                      <a href={extendedProfile.website} target="_blank" rel="noopener noreferrer">
                        {extendedProfile.website}
                      </a>
                    )}
                  </p>
                  
                  <p>
                    <CalendarOutlined style={{ marginRight: '8px' }} />
                    注册时间: {extendedProfile.joinDate}
                  </p>
                </div>
              </div>
            </Col>
            
            {/* 右侧详细信息 */}
            <Col span={16}>
              <Tabs defaultActiveKey="1">
                <TabPane tab="个人简介" key="1">
                  <div style={{ marginBottom: '24px' }}>
                    <Title level={5}>关于我</Title>
                    {isEditing ? (
                      <Form.Item name="bio">
                        <Input.TextArea rows={4} placeholder="介绍一下你自己..." />
                      </Form.Item>
                    ) : (
                      <Paragraph>{extendedProfile.bio}</Paragraph>
                    )}
                  </div>
                  
                  <div style={{ marginBottom: '24px' }}>
                    <Title level={5}>基本信息</Title>
                    <Row gutter={[24, 16]}>
                      <Col span={12}>
                        <div>
                          <Text type="secondary">用户名</Text>
                          <div>
                            {isEditing ? (
                              <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
                                <Input placeholder="用户名" />
                              </Form.Item>
                            ) : (
                              user?.username
                            )}
                          </div>
                        </div>
                      </Col>
                      <Col span={12}>
                        <div>
                          <Text type="secondary">生日</Text>
                          <div>
                            {isEditing ? (
                              <Form.Item name="birthday">
                                <Input placeholder="生日" />
                              </Form.Item>
                            ) : (
                              extendedProfile.birthday
                            )}
                          </div>
                        </div>
                      </Col>
                      <Col span={12}>
                        <div>
                          <Text type="secondary">职业</Text>
                          <div>
                            {isEditing ? (
                              <Form.Item name="occupation">
                                <Input placeholder="职业" />
                              </Form.Item>
                            ) : (
                              extendedProfile.occupation
                            )}
                          </div>
                        </div>
                      </Col>
                    </Row>
                  </div>
                  
                  <div>
                    <Title level={5}>兴趣标签</Title>
                    {isEditing ? (
                      <Form.Item name="interests">
                        <Select
                          mode="tags"
                          style={{ width: '100%' }}
                          placeholder="添加兴趣标签"
                          options={[
                            { value: '低碳生活', label: '低碳生活' },
                            { value: '环保科技', label: '环保科技' },
                            { value: '可持续发展', label: '可持续发展' },
                            { value: '户外活动', label: '户外活动' },
                            { value: '有机农业', label: '有机农业' },
                            { value: '素食主义', label: '素食主义' }
                          ]}
                        />
                      </Form.Item>
                    ) : (
                      <div>
                        {extendedProfile.interests?.map(tag => (
                          <Tag key={tag} color="green" style={{ marginBottom: '8px' }}>
                            {tag}
                          </Tag>
                        ))}
                      </div>
                    )}
                  </div>
                </TabPane>
                
                <TabPane tab="环保成就" key="2">
                  <Row gutter={24} style={{ marginBottom: '24px' }}>
                    <Col span={6}>
                      <Card bordered={false} style={{ textAlign: 'center', background: '#f6ffed' }}>
                        <Statistic 
                          title="绿色能量" 
                          value={user?.greenEnergy || 0} 
                          prefix={<ThunderboltOutlined style={{ color: '#52c41a' }} />} 
                        />
                      </Card>
                    </Col>
                    <Col span={6}>
                      <Card bordered={false} style={{ textAlign: 'center', background: '#e6f7ff' }}>
                        <Statistic 
                          title="碳减排量" 
                          value={extendedProfile.carbonReduction || 0} 
                          suffix="kg" 
                          precision={1}
                        />
                      </Card>
                    </Col>
                    <Col span={6}>
                      <Card bordered={false} style={{ textAlign: 'center', background: '#f9f0ff' }}>
                        <Statistic 
                          title="种植树木" 
                          value={extendedProfile.treesPlanted || 0} 
                          suffix="棵" 
                        />
                      </Card>
                    </Col>
                    <Col span={6}>
                      <Card bordered={false} style={{ textAlign: 'center', background: '#fff2e8' }}>
                        <Statistic 
                          title="完成任务" 
                          value={extendedProfile.tasksCompleted || 0} 
                          suffix="个" 
                        />
                      </Card>
                    </Col>
                  </Row>
                  
                  <div style={{ marginBottom: '24px' }}>
                    <Title level={5}>环保等级</Title>
                    <Progress
                      percent={75}
                      status="active"
                      strokeColor="#52c41a"
                      format={() => '环保先锋'}
                    />
                    <Text type="secondary">再获得125点绿色能量升级到下一等级：环保专家</Text>
                  </div>
                  
                  <div>
                    <Title level={5}>最近获得的成就</Title>
                    <Row gutter={[16, 16]}>
                      <Col span={8}>
                        <Card size="small" bordered={false} style={{ background: '#f6ffed' }}>
                          <div style={{ display: 'flex', alignItems: 'center' }}>
                            <TrophyOutlined style={{ fontSize: '24px', color: '#52c41a', marginRight: '8px' }} />
                            <div>
                              <div>连续打卡达人</div>
                              <Text type="secondary">连续7天完成环保任务</Text>
                            </div>
                          </div>
                        </Card>
                      </Col>
                      <Col span={8}>
                        <Card size="small" bordered={false} style={{ background: '#e6f7ff' }}>
                          <div style={{ display: 'flex', alignItems: 'center' }}>
                            <TrophyOutlined style={{ fontSize: '24px', color: '#1890ff', marginRight: '8px' }} />
                            <div>
                              <div>绿色出行先锋</div>
                              <Text type="secondary">累计步行减碳超过10kg</Text>
                            </div>
                          </div>
                        </Card>
                      </Col>
                      <Col span={8}>
                        <Card size="small" bordered={false} style={{ background: '#f9f0ff' }}>
                          <div style={{ display: 'flex', alignItems: 'center' }}>
                            <TrophyOutlined style={{ fontSize: '24px', color: '#722ed1', marginRight: '8px' }} />
                            <div>
                              <div>种树能手</div>
                              <Text type="secondary">已种植5棵以上的树木</Text>
                            </div>
                          </div>
                        </Card>
                      </Col>
                    </Row>
                  </div>
                </TabPane>
                
                <TabPane tab="活动记录" key="3">
                  <div style={{ marginBottom: '24px' }}>
                    <Title level={5}>最近的环保行动</Title>
                    <ul style={{ listStyleType: 'none', padding: 0 }}>
                      {[
                        { date: '2023-04-05', content: '参与了社区植树活动，种植了2棵树木' },
                        { date: '2023-04-02', content: '完成了"减少一次性用品使用"的挑战任务' },
                        { date: '2023-03-28', content: '连续7天使用公共交通工具出行' },
                        { date: '2023-03-20', content: '参与了社区垃圾分类宣传活动' },
                        { date: '2023-03-15', content: '减少了1.2kg的碳排放量' }
                      ].map((item, index) => (
                        <li key={index} style={{ 
                          padding: '12px 0', 
                          borderBottom: index < 4 ? '1px solid #f0f0f0' : 'none' 
                        }}>
                          <div style={{ display: 'flex', alignItems: 'flex-start' }}>
                            <CheckCircleOutlined style={{ color: '#52c41a', marginRight: '8px', marginTop: '4px' }} />
                            <div>
                              <div>{item.content}</div>
                              <Text type="secondary">{item.date}</Text>
                            </div>
                          </div>
                        </li>
                      ))}
                    </ul>
                  </div>
                </TabPane>
                
                <TabPane tab="环保学习" key="4">
                  <div>
                    <Title level={5}>推荐的环保知识</Title>
                    <Row gutter={[16, 16]}>
                      {[
                        { title: '如何进行家庭垃圾分类?', type: '指南', difficulty: '入门' },
                        { title: '低碳饮食方案与食谱', type: '指南', difficulty: '中级' },
                        { title: '家庭节能减排100招', type: '技巧', difficulty: '入门' },
                        { title: '可持续时尚：如何构建环保衣橱', type: '指南', difficulty: '中级' },
                        { title: '了解碳足迹：日常生活中的碳排放', type: '知识', difficulty: '入门' },
                        { title: '气候变化与我们的未来', type: '知识', difficulty: '高级' }
                      ].map((item, index) => (
                        <Col span={12} key={index}>
                          <Card size="small" hoverable>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                              <div style={{ display: 'flex', alignItems: 'center' }}>
                                <BookOutlined style={{ fontSize: '20px', color: '#1890ff', marginRight: '8px' }} />
                                <div>
                                  <div>{item.title}</div>
                                  <Space>
                                    <Tag color="blue">{item.type}</Tag>
                                    <Tag color="green">{item.difficulty}</Tag>
                                  </Space>
                                </div>
                              </div>
                              <Button type="link">阅读</Button>
                            </div>
                          </Card>
                        </Col>
                      ))}
                    </Row>
                  </div>
                </TabPane>
              </Tabs>
            </Col>
          </Row>
        </Form>
      </Card>
    </div>
  );
};

export default UserProfile; 